import {
  createRouter,
  createWebHistory,
  RouteRecordRaw,
  RouteLocationNormalized
} from 'vue-router'
import ClientLayout from '../layout/Client.vue'

import cache, { CacheType } from '@/utils/cache'

import Client from './client'
import Serve from './serve'

const routes: Array<RouteRecordRaw> = [
  // 用户界面模板
  {
    path: '/',
    name: 'Home',
    component: ClientLayout,
    children: Client
  },
  // 后台登录界面
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/admin/Login.vue')
  },
  // 后台界面模板
  {
    path: '/admin',
    name: 'Admin',
    meta: {
      title: ''
    },
    component: () => import('../layout/Admin.vue'),
    children: Serve
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to: RouteLocationNormalized) => {
  const token = cache.getItem('token', CacheType.session)

  // 判断是否访问后台
  const reg = /^(\/admin)/
  // 访问后台
  if (reg.test(to.path)) {
    if (!token) {
      // 跳到登录
      return '/login'
    }
  }
  // 访问登录
  if (to.path === '/login') {
    if (token) router.go(-1)
  }
})

export default router
